<template>
  <van-field v-model="modelText" v-bind="$attrs" @click="showPicker = true" />
  <van-popup v-model:show="showPicker" round position="bottom">
    <van-picker :columns="items" @cancel="showPicker = false" @confirm="onConfirm" />
  </van-popup>
</template>
<script setup lang="ts">
import { reactive } from "vue";
import { dictMapCache } from "@/api/dict/index";
import type { AntEntry } from "@/api/types";

defineOptions({ inheritAttrs: false });

// 双向绑定值
const model = defineModel<string>();
const modelText = ref("");

// 传递属性
const props = defineProps({
  //字典类型编码
  typeCode: {
    type: String,
    default: ""
  },
  //是否启用状态
  enable: {
    type: Boolean,
    default: true
  }
});

// 可选字典值
const items = reactive([] as AntEntry[]);
dictMapCache(props.typeCode, props.enable).then((res) => {
  res.forEach((dict) => {
    items.push({ value: dict.dictCode, text: dict.dictName });
    if (model.value === dict.dictCode) {
      modelText.value = dict.dictName;
    }
  });
});

const showPicker = ref(false);

const onConfirm = (selected: any) => {
  showPicker.value = false;
  modelText.value = selected.selectedOptions[0].text;
  model.value = selected.selectedOptions[0].value;
};
</script>
